package com.computergames.server.service.getCurrentPlayerStrategy;


import com.computergames.server.domain.Pair;
import com.computergames.server.server.session.RoomSessionFactory;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;



import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


public class Play_GetLandlordCurrentPlayer implements Play_GetCurrentPlayerStrategy{
    private static final String[] PLAYERS = {"A", "B", "C"};
    private final Map<String, Pair<AtomicInteger, Boolean>> roomStates = new ConcurrentHashMap<>();
    @Override
    public boolean getCurrentPlayer(String roomName, String from) {
        Pair<AtomicInteger, Boolean> state = roomStates.computeIfAbsent(roomName, k -> new Pair<>(new AtomicInteger(0), false));
        AtomicInteger currentIdx = state.getValue0();
        boolean isInitialized = state.getValue1();
        List<Channel> channels = RoomSessionFactory.getRoomSession()
                .getMembersChannel(roomName);

        String landlord = null;
        // 获取地主玩家
        for (Channel channel : channels) {
            landlord = (String)channel.attr(AttributeKey.valueOf("LANDLORD")).get();
            if (landlord != null) {
                break;
            }
        }
        // 首个回合必须是地主玩家的回合
        if (currentIdx.get() == 0 && !from.equals(landlord) && !isInitialized) {
            return false;
        }

        // 获取地主的位置
        if(!isInitialized){
            for(int i = 0; i < PLAYERS.length; i++){
                if (PLAYERS[i].equals(landlord)) {
                    currentIdx.set(i);
                    state.setValue1(true);
                    break;
                }
            }
        }

        if (!from.equals(PLAYERS[currentIdx.get()])) {
            return false;
        }

        int currentPlayerIndex = currentIdx.get();
        int nextPlayerIndex = (currentPlayerIndex + 1) % PLAYERS.length;
        currentIdx.set(nextPlayerIndex);
        state.setValue0(currentIdx);
        return true;

    }
}
